from flask import Blueprint, request, jsonify, current_app
from utils.response import success, error
from config import config
import qqmusic_api.song as song_module
from qqmusic_api.song import SongFileType
import httpx
from pathlib import Path

# 创建蓝图
download_bp = Blueprint("download", __name__)
def get_file_extension(file_type):
    extension_mapping = {
        SongFileType.FLAC: ".flac",
        SongFileType.MP3_320: ".mp3",
        SongFileType.ACC_192: ".m4a",
        SongFileType.MP3_128: ".mp3",
        SongFileType.ACC_96: ".m4a",
        SongFileType.ACC_48: ".m4a",
        SongFileType.MASTER: ".flac",
        SongFileType.ATMOS_2: ".flac",
        SongFileType.ATMOS_51: ".flac",
        SongFileType.OGG_640: ".ogg",
    }
    return extension_mapping.get(file_type, ".mp3")

@download_bp.route("/download", methods=["POST"])
async def download_sef():
    if not request.is_json:
        return error(message="请求格式不正确")
    data = request.json
    mid = data.get("mid")
    file_name = data.get("file_name")
    file_type = data.get("file_type")

    if not mid:
        return error(message="mid 是必填项")
    if not file_type:
        return error(message="file_type 是必填项")

    file_type_mapping = {
        "size_flac": SongFileType.FLAC,
        "size_320mp3": SongFileType.MP3_320,
        "size_192aac": SongFileType.ACC_192,
        "size_128mp3": SongFileType.MP3_128,
        "size_96aac": SongFileType.ACC_96,
        "size_48aac": SongFileType.ACC_48,
        "size_new_0": SongFileType.MASTER,
        "size_new_1": SongFileType.ATMOS_2,
        "size_new_2": SongFileType.ATMOS_51,
        "size_new_5": SongFileType.OGG_640,
    }

    file_type_dood = file_type_mapping.get(file_type, SongFileType.MP3_320)
    try:
        urls = await song_module.get_song_urls(mid=[mid], file_type=file_type_dood, credential=config.CREDENTIAL)
        print(f"urls: {urls}")
        if not urls or mid not in urls:
            current_app.logger.warning("无法获取歌曲下载链接")
            return error(message="无法获取歌曲下载链接")

        url_info = urls[mid]
        url = url_info[0] if isinstance(url_info, tuple) else url_info
        if not url:
            current_app.logger.warning("无法获取歌曲下载链接")
            return error(message="无法获取歌曲下载链接")

        with httpx.Client() as client:
            with client.stream("GET", url) as response:
                if response.status_code != 200:
                    return error(message=f"HTTP错误: {response.status_code}")
                total_size = int(response.headers.get("Content-Length", 0))
                if total_size == 0:
                    return error(message="暂无地址下载")

                save_dir = Path("C:/music")
                save_dir.mkdir(parents=True, exist_ok=True)
                ext = get_file_extension(file_type_dood)
                file_path = save_dir / f"{file_name}{ext}"
                downloaded = 0
                with open(file_path, "wb") as f:
                    for chunk in response.iter_bytes(1024 * 10):  
                        if chunk:
                            f.write(chunk)
                            downloaded += len(chunk)
                            if total_size > 0:
                                percent = min(100, int(downloaded / total_size * 100))
                                print(f"Downloading... {percent}%")

        return success(data={"file_path": str(file_path)}, message="下载成功")
    except httpx.RequestError as e:
        return error(message=f"网络请求失败: {e}")
    except Exception as e:
        return error(message=f"发生错误: {e}")